package pay

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"log"
	"net/http"
	"strconv"
	"time"
)

func NewPayClient() *alipay.Client {
	APP_ID := "9021000131619667"
	//公钥
	PUBLIC_KEY := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGFDVI+EQXkmuE59Yri6d3p19dw6IlXzS+3H0++ijL5W8hcaTdqM+3AY3/DcoTAg9YXgHmzt9+7cE98vUkrqWcZqhvguSwIB363vDepudXs2MKrsQnn4zM7yo5JaWQ/Npizb9UMl4XZwPrNtRUaItkLKY9g/HgCLfEq5A93AkP+atz1iUJij8ddG2ld9tA/MEfzbtX3kmlymhOOoOOGY6yaQSVaCCBSqd4dpvw0tWSS0GakSQ3P8NxtZLQl4/li7h+KYdvnc1/xC0jEaQOrKFmGIp15n0xP4s4EJgS0ZjqfJ1UVlzIM+EcnOiLHuULUdPzEi81d2mFwiV1XYOp7ZHQIDAQAB"
	//私钥
	PRIVATE_KEY := "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDkHOx7yNrH0JLHv5ldwk6yxomlcCCB3t+bi1xBJHBoAcxSasOFZPpdoohVkEA+1yxK7ZUIZtayiQeUXDtndc1Bqif24fqCFzS91EAaBVppobCwpUK8fGs/im2q7JPdpeIYR3gDg/uyidGTMsMNORzpm5XKiYawajV1/45VuzEwqE9J2D2KsapU1MmSUNdynSOyKWJ9ZF+cRC6WmnNE7tB6/obtaGx0cMswIdNkXuq/mFZfrCWAH+07LfB6kQDqY0IowUUegYPO2qE6F0ys9qx++4sB+4nqNVSG6JhPMioPOFG57O94HA88WZa2O+GM0qUjlQRm/zI/CoK5ozcRNssrAgMBAAECggEAA6JCUiZ89bno3K28r7Wss0ReZPhITElUnpG1woPmFoIQ0y9INhPJuTwhl9tYaqfa2Ma4HQ4mVWnBaSee+qLxxh4DzPcEmpXsDSoYa1GygwREYEwBqCcDPlviK1rhcCJ4W5Kn4sZzeACiCg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2WcjESw=="

	var client, err = alipay.New(APP_ID, PRIVATE_KEY, false)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	if err = client.LoadAliPayPublicKey(PUBLIC_KEY); err != nil {
		fmt.Println(err)
		return nil
	}
	return client
}

func Pays(orderSnc string, price string) (string, error) {
	client := NewPayClient()
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "https://915br527pq19.vicp.fun/alipay/callback" //设置支付宝异步通知的回调URL，当支付状态发生变化时，支付宝会向该URL发送通知。
	p.ReturnURL = "https://915br527pq19.vicp.fun/alipay/callback" //设置支付宝同步通知的回调URL，支付完成后用户将跳转回该URL
	p.Subject = "支付" + orderSnc                                   //标题
	p.OutTradeNo = orderSnc                                       //传递一个唯一单号
	p.TotalAmount = price                                         //金额
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"                      //产品代码
	currentTime := time.Now()
	unixTimestamp := currentTime.Unix()
	p.TimeoutExpress = strconv.FormatInt(unixTimestamp, 10) //设置超时时间，即订单有效期，以Unix时间戳形式表示。
	p.Body = "描述"                                           //设置订单描述信息。
	var str, err = client.TradeWapPay(p)
	if err != nil {
		return "", err
	}
	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	fmt.Println(str.String())
	return str.String(), nil
}

// Refund 退款
func Refund(tradeNo string, refundAmount string) (*alipay.TradeRefundRsp, error) {
	client := NewPayClient()
	var p = alipay.TradeRefund{}
	p.RefundAmount = "10.00"
	p.TradeNo = "208872101398674"
	refunds, err := client.TradeRefund(context.Background(), p)
	if err != nil {
		return nil, err
	}
	return refunds, nil
}

// Callback 回调
func Callback(writer http.ResponseWriter, request *http.Request) string {
	client := NewPayClient()
	request.ParseForm()
	if err := client.VerifySign(request.Form); err != nil {
		log.Println("回调验证签名发生错误", err)
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write([]byte("回调验证签名发生错误"))
		return "0"
	}

	log.Println("回调验证签名通过")

	// 示例一：使用已有接口进行查询
	var outTradeNo = request.Form.Get("out_trade_no")
	var p = alipay.TradeQuery{}
	p.OutTradeNo = outTradeNo

	rsp, err := client.TradeQuery(context.Background(), p)
	if err != nil {
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write([]byte(fmt.Sprintf("验证订单 %s 信息发生错误: %s", outTradeNo, err.Error())))
		return "0"
	}

	if rsp.IsFailure() {
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write([]byte(fmt.Sprintf("验证订单 %s 信息发生错误: %s-%s", outTradeNo, rsp.Msg, rsp.SubMsg)))
		return "0"
	}
	writer.WriteHeader(http.StatusOK)
	writer.Write([]byte(fmt.Sprintf("订单 %s 支付成功", outTradeNo)))
	return outTradeNo
}
